package com.newthread.android.util;

import android.content.Context;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Created by jindongping on 15/3/1.
 */
public class RootManger {

    private static RootManger instance = null;
    private Process process;

    public static RootManger getInstance() {
        if (instance != null) {
            return instance;
        }
        instance = new RootManger();
        return instance;

    }

    private RootManger() {

    }

    public boolean getRootPM() {
        try {
            process = Runtime.getRuntime().exec("su");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean excuteMsg(String[] commands) {
        DataOutputStream dataOutputStream = null;
        getRootPM();
            try {
                dataOutputStream = new DataOutputStream(process.getOutputStream());
                int length = commands.length;
                for (int i = 0; i < length; i++) {
                    dataOutputStream.writeBytes(commands[i] + "\n");
                }
                dataOutputStream.writeBytes("exit\n");
                dataOutputStream.flush();
                process.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                try {
                    if (dataOutputStream != null) {
                        dataOutputStream.close();
                    }
                    process.destroy();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        return true;
    }

    public void writeApkToSystemAPP(Context context) {
        String fileName = "*";
        String filePath = "/data/app/" + context.getPackageName() + "-1/" + fileName;
        String[] commands = {"busybox mount -o remount,rw /system",
                "busybox mkdir /system/app/" + context.getPackageName() + "-1",
                "busybox cp -R " + filePath + " /system/app/" + context.getPackageName() + "-1",
                "busybox chmod -R 755 /system/app/" + context.getPackageName() + "-1"};
        excuteMsg(commands);
    }

}
